// lib/entropy.js
function calculateEntropy(probabilities) {
  return probabilities.reduce((entropy, p) => {
    if (p > 0) {
      return entropy - p * Math.log2(p);
    }
    return entropy;
  }, 0);
}

function validateProbabilities(probabilities) {
  const sum = probabilities.reduce((sum, p) => sum + p, 0);
  return probabilities.every(p => p >= 0 && p <= 1) && Math.abs(sum - 1) < 1e-10;
}

function parseArguments(args) {
  const parts = args.split(/[,\s]+/).filter(Boolean);

  if (parts.length < 2) {
    throw new Error('命令行参数错误：概率数据少于两个！');
  }

  const probabilities = parts.map(p => {
    const num = parseFloat(p);
    if (isNaN(num)) {
      throw new Error('请输入数字！');
    }
    if (num < 0) {
      throw new Error('请输入大于0的数！');
    }
    if (num > 1) {
      throw new Error('请输入小于1的数！');
    }
    return num;
  });

  if (!validateProbabilities(probabilities)) {
    throw new Error('概率空间不封闭，概率和不等于1！');
  }

  return probabilities;
}

module.exports = {
  calculateEntropy,
  validateProbabilities,
  parseArguments
};